package com.arvato.minipro.service.mall;

import java.util.SortedMap;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.minipro.bean.bean_dto.common.WxPayDto;
import com.arvato.common.config_bean.WxPayConfig;
import com.arvato.common.util.WxPayUtil;

@Service
@Transactional
public class PayService {
	
	private Logger logger = LoggerFactory.getLogger(PayService.class);
	
	@Autowired
	CommodityService commodityService;
	/**
	 * 统一下单 参数很简单 一句话 那个人(openId),付了多少钱(money),对应的订单号是多少(orderNo自定义)
	 * @param userId
	 * @param openId
	 * @param orderId 
	 * @param commodityList
	 * @return
	 */
	public Result prePay(String openId, String orderNo, String orderId, int payment) {
		Result result = new Result(false);
		// 计算订单的总额
		// 生成订单号：时间戳
		String currTime = WxPayUtil.getCurrTime();
		// 8位日期
		String strTime = currTime.substring(8, currTime.length());
		// 四位随机数
		String strRandom = WxPayUtil.buildRandom(4) + "";
		// 10位序列号,可以自行调整。
		String nonceStr = strTime + strRandom;
		// 这里notify_url是 支付完成后微信发给该链接信息，可以判断会员是否支付成功，改变订单状态等。
		String notifyUrl = "https://minipro.arvatocrm.cn/arvato/mall/order/notify";
		// 自定义的附加数据(随便写有用的，不会影响支付结果)，原样返回。
		String attach = orderId;
		String detail = "arvato购买测试";
		String body = "arvato护肤精品";
		SortedMap<String, String> packageParams = new TreeMap<String, String>();
		String appId = WxPayConfig.APPID;
		packageParams.put("appid", appId);
		packageParams.put("attach", attach);// 附加数据
		packageParams.put("body", body);// 商品描述
		packageParams.put("detail", detail);
		String matchId = WxPayConfig.MATCHID;
		packageParams.put("mch_id", matchId);// 商户号
		packageParams.put("nonce_str", nonceStr);// 随机数
		packageParams.put("notify_url", notifyUrl);
		packageParams.put("openid", openId);
		packageParams.put("out_trade_no", orderNo);// 商户订单号
		String createOrderIP = WxPayConfig.CREATE_ORDER_IP;
		packageParams.put("spbill_create_ip", createOrderIP);// 订单生成的机器 IP
		packageParams.put("total_fee", payment + "");// 总金额
		packageParams.put("trade_type", "JSAPI");
		// 商户的密钥字符串
		String key = WxPayConfig.KEY;
		String sign = WxPayUtil.createSign(packageParams, key);
		String xml = "<xml>" + "<appid>" + appId + "</appid>" + "<attach>" + attach + "</attach>" + "<body><![CDATA["
				+ body + "]]></body>" + "<detail><![CDATA[" + detail + "]]></detail>" + "<mch_id>" + matchId
				+ "</mch_id>" + "<nonce_str>" + nonceStr + "</nonce_str>" + "<sign>" + sign + "</sign>" + "<notify_url>"
				+ notifyUrl + "</notify_url>" + "<openid>" + openId + "</openid>" + "<out_trade_no>" + orderNo
				+ "</out_trade_no>" + "<spbill_create_ip>" + createOrderIP + "</spbill_create_ip>" + "<total_fee>"
				+ payment + "</total_fee>" + "<trade_type>JSAPI</trade_type>" + "</xml>";
		String prepay_id = "";
		try {
			String wxPayUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
			prepay_id = WxPayUtil.getPayNo(wxPayUrl, xml);
			if (prepay_id.equals("")) {
				// 错误提示
				logger.info("统一支付接口获取预支付订单出错");
				return result;			
			} else {
				result.setResult(true);
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		SortedMap<String, String> finalpackage = new TreeMap<String, String>();
		String timestamp = WxPayUtil.getTimeStamp();
		String packages = "prepay_id=" + prepay_id;
		finalpackage.put("appId", appId);
		finalpackage.put("nonceStr", nonceStr);
		finalpackage.put("package", packages);
		finalpackage.put("signType", "MD5");
		finalpackage.put("timeStamp", timestamp);
		String finalsign = WxPayUtil.createSign(finalpackage, key);
		WxPayDto dto = new WxPayDto();
		dto.setNonceStr(nonceStr);
		dto.setPackage_(packages);
		dto.setPaySign(finalsign);
		dto.setSignType("MD5");
		dto.setTimeStamp(timestamp); 
		result.setData(dto);
		return result;
	}

}
